/*
 * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.yangtools.yang.data.impl.schema;

import static java.util.Objects.requireNonNull;

import com.google.common.collect.Interner;
import java.util.Optional;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
import org.opendaylight.yangtools.yang.data.util.LeafInterner;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;

final class InterningLeafNodeBuilder<T> extends ImmutableLeafNodeBuilder<T> {
    private final Interner<LeafNode<T>> interner;

    private InterningLeafNodeBuilder(final Interner<LeafNode<T>> interner) {
        this.interner = requireNonNull(interner);
    }

    static <T> @Nullable InterningLeafNodeBuilder<T> forSchema(final @Nullable DataSchemaNode schema) {
        if (schema instanceof LeafSchemaNode) {
            final Optional<Interner<LeafNode<T>>> interner = LeafInterner.forSchema((LeafSchemaNode)schema);
            if (interner.isPresent()) {
                return new InterningLeafNodeBuilder<>(interner.get());
            }
        }
        return null;
    }

    @Override
    public LeafNode<T> build() {
        return interner.intern(super.build());
    }
}
